# -*- coding: utf-8 -*-
# @Time    : 2022/6/27 16:58
# @Author  : zyw
# @Email   : panda_kings@163.com
# @File    : comment.py
import json

from flask import Blueprint,jsonify
from flask_restful import Api,Resource,reqparse,marshal

from common.utils.jwt_utils import verify_jwt
from common.models.courses import *
from common.models.users import UserModels
from common.model_fields.course_fields import *
from common.model_fields.user_fields import user_fields
from common.utils.login_jwt import login_required

comment_bp = Blueprint('comment', __name__, url_prefix='/comment')
api = Api(comment_bp)


class CommentResource(Resource):
    def post(self):
        """
        发布评论
        """
        parser = reqparse.RequestParser()
        params = ['cid','content','token','ques_id','reply']
        for i in params:
            parser.add_argument(i)
        args = parser.parse_args()
        cid = args.get('cid')
        content = args.get('content')
        token = args.get('token')
        ques_id = args.get('ques_id')
        reply = args.get('reply')
        # 验证token
        print('token--->', token)
        print(token[4:])
        try:
            payload = verify_jwt(token[4:])
            print(payload)
        except Exception as e:
            # 校验错误,先登录
            return jsonify(message='请先登录',code=401)
        # 获取用户id
        user_id = payload['user_id']
        if cid:
            # 此时cid有值,说明是文章的评论
            try:
                comment= Comment(user=uid, comment_count=content, parent_id=cid, course=qid)
                db.session.add(comment)
                db.session.commit()

            except Exception as e:
                return jsonify(message="添加评论失败", code=500)
            Comment.query.filter_by(id=cid).update({'reply_count': comment.reply_count + 1})
            db.session.commit()
            return jsonify(message="添加评论成功", code=200)
        if reply:
            # 说明是评论的回复
            try:
                comment = Comment(comment_content=content,
                                  user=user_id,
                                  parent_id=reply)
                db.session.add(comment)
                db.session.commit()
            except Exception as e:
                return jsonify(message="回复评论失败", code=500)
            # 修改回复的数量
            Comment.query.filter_by(id=reply).update({'reply_count':comment.reply_count + 1})
            db.session.commit()
            return jsonify(message="添加评论成功", code=200)


class CommentsInfo(Resource):

    @login_required
    def get(self):
        """获取所有的评论"""
        parser = reqparse.RequestParser()
        parser.add_argument('course_id')
        args = parser.parse_args()
        cid = args.get('course_id')
        print('cid---->', cid)
        if not cid:
            return jsonify(message="获取课程评论失败",code=400)
        # 根据课程id 获取所有评论
        try:
            comments = Comments.query.filter_by(course=int(cid)).all()
            print("comments``````",comments)
        except Exception as e:
            return jsonify(message="此课程已经不存在",code=400)
        comments = json.loads(json.dumps(marshal(comments, comment_fields)))
        for i in comments:
            user = UserModels.query.filter_by(uid=i["user"]).first()
            user = marshal(user, user_fields)
            i["user_info"] = user

            if i['parent_id']:
                # 此时说明有评论的回复
                childs_comments = Comments.query.filter_by(parent_id=i['id']).all()
                child_comments = marshal(childs_comments, comment_fields)
                for j in child_comments:
                    user = UserModels.query.filter_by(uid=i["user"]).first()
                    user = marshal(user, user_fields)
                    j["user_info"] = user
                i["childlist"] = child_comments
        return jsonify(message="ok！", code=200, data=comments)


api.add_resource(CommentResource, '/add_comment')
api.add_resource(CommentsInfo, '/get_comment')